package com.suredy.app.index.ctrl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.suredy.Constants;
import com.suredy.core.ctrl.BaseCtrl;
import com.suredy.security.entity.User2RoleEntity;
import com.suredy.security.model.User;
import com.suredy.security.model.User2Role;
import com.suredy.security.service.User2RoleSrv;
import com.suredy.security.service.UserSrv;
import com.suredy.tools.checkcode.SuredyLoginCheckImage;

@Controller
public class LoginCtrl extends BaseCtrl {

	@Autowired
	private SuredyLoginCheckImage suredyLoginCheckImage;

	@Autowired
	private UserSrv userSrv;

	@Autowired
	private User2RoleSrv user2RoleSrv;

	@Value("${system.name}")
	private String SYS_NAME;

	@Value("${system.logo}")
	private String SYS_LOGO;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginIndex() {
		this.getSession();
		this.setSessionAttribute("sys_name", this.SYS_NAME);
		this.setSessionAttribute("sys_logo", this.SYS_LOGO);
		return "login";
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout() {
		this.clearSession();
		return "redirect:login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String doLogin(String userCode, String password, Boolean startupFlow, RedirectAttributes attributes) {
		if (StringUtils.isBlank(userCode) || StringUtils.isBlank(password)) {
			attributes.addFlashAttribute("err_msg", "请正确填写用户名与密码");
			attributes.addFlashAttribute("uniqueCode", userCode);

			return "redirect:login";
		}

		User user = this.userSrv.getUser(userCode);

		if (user == null || !password.equals(user.getPassword())) {
			attributes.addFlashAttribute("err_msg", "用户名与密码不匹配");
			attributes.addFlashAttribute("uniqueCode", userCode);

			return "redirect:login";
		}

		// 存放到session中
		this.setUser(user);
		this.setRoles(user.getId());

		if (startupFlow) {
			// TODO startup workflow server.
		}

		return "redirect:index";
	}

	@RequestMapping("/check-img/{width}/{height}")
	public void checkImg(HttpServletResponse response, @PathVariable int width, @PathVariable int height) {
		try {
			String code = this.suredyLoginCheckImage.write(response.getOutputStream(), width, height);

			this.setSessionAttribute(Constants.SESSION_LOGIN_CHECK_CODE, code);
		} catch (IOException e) {
		}
	}

	private void setRoles(String userId) {
		List<User2RoleEntity> roles = this.user2RoleSrv.getByUser(userId);

		if (roles == null || roles.isEmpty())
			return;

		List<User2Role> rs = new ArrayList<User2Role>();

		for (User2RoleEntity r : roles) {
			rs.add(r.toVO());
		}

		if (rs.isEmpty())
			return;

		super.setRoles(rs);
	}

}
